package edu.zqu.collegeField.common.utils;

import com.google.common.collect.Lists;
import edu.zqu.common.utils.StringUtils;
import org.dozer.DozerBeanMapper;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.TypeMappingOptions;

import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.List;

/**
 * @author 廖森
 * @Date 2020/6/28/004.
 */
public class BeanMapper {
    /**
     * 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        if (StringUtils.isNotNull(source)) {
            return dozer.map(source, destinationClass);
        } else return null;
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        if (StringUtils.isNotEmpty(sourceList)) {
            List<T> destinationList = Lists.newArrayList();
            for (Object sourceObject : sourceList) {
                T destinationObject = dozer.map(sourceObject, destinationClass);
                destinationList.add(destinationObject);
            }
            return destinationList;
        } else {
            return null;
        }
    }

    /**
     * 基于Dozer将对象A的值拷贝到对象B中.
     */
    public static void copy(Object source, Object destinationObject) {
        dozer.map(source, destinationObject);
    }

    public static void copyPropertiesNotNull(final Object sources, final Object destination) {
        WeakReference weakReference = new WeakReference(new DozerBeanMapper());
        DozerBeanMapper mapper = (DozerBeanMapper) weakReference.get();

        mapper.addMapping(new BeanMappingBuilder() {

            @Override
            protected void configure() {
                mapping(sources.getClass(), destination.getClass(), TypeMappingOptions.mapNull(false), TypeMappingOptions.mapEmptyString(false));
            }
        });
        mapper.map(sources, destination);
        mapper.destroy();
        weakReference.clear();
    }
}
